import {Component, Input, OnInit} from '@angular/core';
import * as moment from "moment";
import {FetchService} from "../../../../core/net/fetch.service";
import * as _ from "lodash";
import {format, startOfMonth} from 'date-fns';
import { UtilService } from '../../../../core/util/util.service';

@Component({
    selector: 'app-hr-multi-statistics',
    templateUrl: './hr-multi-statistics.component.html',
    styleUrls: ['./hr-multi-statistics.component.scss', '../hr-statistics.component.scss']
})
export class HrMultiStatisticsComponent implements OnInit {
    listData = [];
    stadiaCode: string; //  当前测站编码
    defaultKeys = [];
    processOpt: any = {
        toolbox: {
            show: true,
            feature: {
                saveAsImage: {
                    show: true,
                    excludeComponents: ['toolbox'],
                    pixelRatio: 2
                }
            }
        },
        tooltip: {
            trigger: "axis",
            axisPointer: {
                type: "cross",
                animation: false,
                label: {
                    backgroundColor: "#505765"
                }
            }
        },
        legend: {
            data: [],
            bottom: 10
        },
        xAxis: {
            type: "category",
            data: []
        },
        yAxis: [
            {
                name: "",
                type: "value"
            }
        ],
        series: [
            {
                name: "",
                type: "line",
                smooth: true,
                data: []
            },
        ]
    };
    levelOptChange: any = {};
    fluxOptChange: any = {};
    tableData = [];

    barOpt: any = {
        toolbox: {
            show: true,
            feature: {
                saveAsImage: {
                    show: true,
                    excludeComponents: ['toolbox'],
                    pixelRatio: 2
                }
            }
        },
        tooltip: {
            trigger: "axis",
            axisPointer: {
                type: "shadow"
            }
        },
        legend: {
            data: [],
            bottom: 0
        },
        grid: {
            top: "10%",
            bottom: "8%",
            left: "6%",
            right: "4%",
            containLabel: true
        },
        xAxis: {
            type: "category",
            data: []
        },
        yAxis: {
            name: "耗水量",
            type: "value"
        },
        series: []
    };
    barOptChange: any = {};
    tableHead = [];

    @Input()
    get dateModal() {
        // this.queryInfo();
        return this._dateModal;
    }

    set dateModal(val) {
        this._dateModal = val;
        if (this.stadiaCode) {
            this.queryInfo();
        }
    }

    // tslint:disable-next-line:variable-name
    _dateModal = [startOfMonth(new Date()), new Date()];

    levelEchartsIntance: any;
    fluxEchartsIntance: any;
    constructor(private fetchService: FetchService,
                private util: UtilService) {
    }

    ngOnInit(): void {
        this.fetchService.post<any>('wrs/wrsBrstadia/list', {}).subscribe(res => {
            console.log(res);
            res.list.forEach(item => {
                item.title = item.stadiaName;
                item.key = item.stadiaCode;
                item.isLeaf = true;
            });
            this.listData = res.list;
            this.defaultKeys = [this.listData[0].key];
            this.stadiaCode = this.defaultKeys.join(',');
            this.queryInfo();
        });
    }
    private calcYAxisData(type: string, max: number, min: number): number {
        if (type === 'max') {
            return max + (max - min) / 2;
        } else if (type === 'min') {
            return (min - (max - min)) >= 0 ? +(min - (max - min)) : 0;
        }
    }
    levelChartInit(ec) {
        this.levelEchartsIntance = ec;
    }
    fluxChartInit(ec) {
        this.fluxEchartsIntance = ec;
    }
    selectedAreaChanged(event): void {
        // console.log(event);
        this.stadiaCode = event.checkedKeys.map(item => {
            return item.key;
        }).join(',');
        this.queryInfo();
    }

    queryInfo(): void {
        this.getLevelAndFluxData();
    }

    //  获取多站水位流量曲线
    getLevelAndFluxData(): void {
        const params = {
            stadiaCode: this.stadiaCode,
            startTime: moment(this.dateModal[0]).format('YYYY-MM-DD'),
            endTime: moment(this.dateModal[1]).format('YYYY-MM-DD')
        };
        this.fetchService.post('wrs/wrsBrstadia/queryStadiasStatistics', params).subscribe(res => {
            if (res) {
                const oriKeys = Object.keys(res);
                _.remove(oriKeys, i => {
                    return i === 'useFlux';
                });
                const legendArr = oriKeys;
                this.tableHead = legendArr.map(item => {
                    return {
                        title: item,
                        levelProp: item + '_level',
                        fluxProp: item + '_flux'
                    };
                });
                let whMax = 0;
                let whMin = 0;
                let flowMax = 0;
                let flowMin = 0;
                const seriesLevelData = legendArr.map(o => {
                    const seriesData = [];
                    res[o].forEach(item => {
                        seriesData.push(item['Water_Height']);
                    });
                    whMax = this.util.max(seriesData.concat(whMax));
                    whMin = this.util.min(seriesData.concat(whMin));
                    return {
                        name: o,
                        type: 'line',
                        smooth: true,
                        data: seriesData
                    };
                });
                const seriesFluxData = legendArr.map(o => {
                    const seriesData = [];
                    res[o].forEach(item => {
                        seriesData.push(item['Flux_Income']);
                    });
                    flowMax = this.util.max(seriesData.concat(flowMax));
                    flowMin = this.util.min(seriesData.concat(flowMin));
                    return {
                        name: o,
                        type: 'line',
                        smooth: true,
                        data: seriesData
                    };
                });
                const commonOpt = {
                    toolbox: {
                        show: true,
                        feature: {
                            saveAsImage: {
                                show: true,
                                excludeComponents: ['toolbox'],
                                pixelRatio: 2
                            }
                        }
                    },
                    tooltip: {
                        trigger: "axis",
                        axisPointer: {
                            type: "cross",
                            animation: false,
                            label: {
                                backgroundColor: "#505765"
                            }
                        }
                    },
                    legend: {
                        data: legendArr
                    },
                    xAxis: {
                        data: res[legendArr[0]].map(o => {
                            return o['date'];
                        })
                    },
                };
                const levelOpt = {
                    yAxis: {
                        name: "水位（m）",
                        min: Math.floor(this.calcYAxisData('min', whMax, whMin)),
                        max: Math.ceil(this.calcYAxisData('max', whMax, whMin)),
                    },
                    series: seriesLevelData
                };
                const fluxOpt = {
                    yAxis: {
                        name: "流量（m³/s）",
                        min: Math.floor(this.calcYAxisData('min', flowMax, flowMin)),
                        max: Math.ceil(this.calcYAxisData('max', flowMax, flowMin)),
                    },
                    series: seriesFluxData
                };
                this.levelOptChange = {...commonOpt, ...levelOpt};
                this.fluxOptChange = {...commonOpt, ...fluxOpt};

                this.levelEchartsIntance.setOption(this.levelOptChange, true);
                this.fluxEchartsIntance.setOption(this.fluxOptChange, true);

                this.barOptChange = {
                    xAxis: {
                        data: res[legendArr[0]].map(o => {
                            return o['date'];
                        })
                    },
                    series: [
                        {
                            name: '耗水量（亿m³）',
                            type: "bar",
                            data: res['useFlux'].map(item => {
                                return item['useFlux'];
                            })
                        }
                    ]
                };
                const tableData = res[legendArr[0]].map(o => {
                    return {
                        date: o['date']
                    };
                });

                this.tableHead.forEach(key => {
                    tableData.forEach((item, index) => {
                        const nameObj = res[key.title];
                        item[key.levelProp] = nameObj[index]['Water_Height'];
                        item[key.fluxProp] = nameObj[index]['Flux_Income'];
                        item['useWater'] = res['useFlux'][index].useFlux;
                    });
                });

                this.tableData = tableData;
            }
        });
    }
}
